<template>
  <div
    class="dept-container"
    style="width: 100%; height: 100%; background: #f6f8f9 !important"
  >
    <Splitpanes class="default-theme hs">
      <Pane size="20">
        <div style="width: 100%; padding: 10px">
          <div
            style="padding: 20px; color: #000; border-bottom: 1px solid #f4f5f6"
          >
            机构目录
          </div>
          <div class="container" :style="'height:' + height + 'px;'">
            <el-scrollbar>
              <el-tree
                ref="myTree"
                node-key="id"
                :load="loadNode"
                lazy
                :props="defaultProps"
                current-node-key
                highlight-current
                :expand-on-click-node="false"
                :allow-drop="allowDrop"
                :allow-drag="allowDrag"
                :draggable="hasPermission({ permission: ['system:dept:move'] })"
                @node-drop="nodeDrop"
                @node-click="handleNodeClick"
              >
                <template #default="{ node, data }">
                  <span
                    class="custom-tree-node"
                    @mouseenter="mouseenter($event, data)"
                    @mouseleave="mouseleave(data)"
                  >
                    <span>
                      {{ node.label }}
                    </span>
                    <div class="toolsoperator">
                      <div
                        v-if="data.show"
                        style="position: fixed; z-index: 10000000 !important"
                        :style="style"
                      >
                        <el-button
                          v-permissions="{
                            permission: ['system:dept:create'],
                          }"
                          style="margin-left: 5px"
                          type="primary"
                          circle
                          :icon="Plus"
                          @click="handleEdit(data, 'add')"
                        />
                        <el-button
                          v-permissions="{
                            permission: ['system:dept:delete'],
                          }"
                          style="margin-left: 5px"
                          type="danger"
                          :disabled="data.leaf ? false : true"
                          circle
                          :icon="Delete"
                          @click="handleDelete(data)"
                        />
                      </div>
                    </div>
                  </span>
                </template>
              </el-tree>
            </el-scrollbar>
          </div>
        </div>
      </Pane>
      <Pane>
        <div style="width: 100%; padding: 10px">
          <vxe-grid
            ref="xGrid"
            border
            stripe
            resizable
            keep-source
            auto-resize
            :loading="listLoading"
            :column-config="{ resizable: true }"
            :export-config="{}"
            :height="height + 60"
            :columns="tableColumn"
            align="center"
            :row-config="{ keyField: 'id', isCurrent: true, isHover: true }"
          >
            <template #form>
              <vxe-form
                ref="queryform"
                title-align="right"
                title-width="100"
                prevent-submit
              >
                <vxe-form-item title="机构名称" span="8">
                  <template #default>
                    <el-input
                      v-model="listQuery.name"
                      placeholder="请输入机构名称"
                      style="width: 200px"
                      clearable
                    />
                  </template>
                </vxe-form-item>
                <vxe-form-item span="8">
                  <el-button :icon="Search" @click="handleQueryClick">
                    搜索
                  </el-button>
                  <el-button
                    type="primary"
                    :icon="Plus"
                    @click="handleEdit('', 'add')"
                  >
                    增加
                  </el-button>
                </vxe-form-item>
              </vxe-form>
            </template>
            <template #formatDeptType="{ row }">
              {{ formatDeptType(row) }}
            </template>
            <template #status="{ row }">
              {{ row.status == 0 ? '可用' : '停用' }}
            </template>
            <template #operation="{ row }">
              <el-button
                v-permissions="{ permission: ['system:dept:update'] }"
                type="primary"
                :icon="Edit"
                link
                @click="handleEdit(row, 'edit')"
              >
                编辑
              </el-button>
              <el-button
                v-permissions="{ permission: ['system:dept:delete'] }"
                type="danger"
                :icon="Delete"
                link
                :disabled="row.leaf ? false : true"
                @click="handleDelete(row)"
              >
                删除
              </el-button>
            </template>
          </vxe-grid>
        </div>
      </Pane>
    </Splitpanes>
    <edit ref="editRef" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { Pane, Splitpanes } from 'splitpanes'
  import 'splitpanes/dist/splitpanes.css'
  import { hasPermission } from '@/utils/permission'
  import { deleteDept, getDeptPage, getMove } from '@/api/system/dept/index'
  import { Delete, Edit, Plus, Search } from '@element-plus/icons-vue'

  export default defineComponent({
    name: 'Dept',
    components: {
      Edit: defineAsyncComponent(() => import('./components/deptEdit')),
      Splitpanes,
      Pane,
    },
    setup() {
      const $baseConfirm = inject('$baseConfirm')
      const $baseMessage = inject('$baseMessage')
      const $baseTableHeight = inject('$baseTableHeight')
      const $XEUtils = inject('$XEUtils')

      const state = reactive({
        height: $baseTableHeight(0),
        myTree: null,
        editRef: 'editRef',
        xGrid: null,
        data: [],
        defaultProps: {
          children: 'children',
          label: 'name',
          isLeaf: 'leaf',
        },
        list: [],
        listLoading: false,
        lazyLoading: false,
        typeOptions: [
          { value: 0, label: '局级单位' },
          { value: 1, label: '处室' },
          { value: 2, label: '二级单位' },
          { value: 3, label: '科室' },
          { value: 4, label: '项目部' },
          { value: 5, label: '井队' },
          { value: 6, label: '其它' },
        ],
        listQuery: { name: '' },
        tableColumn: [
          { type: 'seq', width: 50 },
          {
            field: 'name',
            title: '名称',
            showOverflow: true,
            width: 320,
          },
          {
            field: 'code',
            title: '编码',
            showOverflow: true,
            width: 140,
          },
          {
            field: 'phone',
            title: '联系电话',
            showOverflow: true,
            width: 140,
          },
          {
            field: 'type',
            title: '类型',
            showOverflow: true,
            width: 120,
            slots: { default: 'formatDeptType' },
          },
          {
            field: 'sort',
            title: '排序',
            width: 70,
          },
          {
            field: 'status',
            title: '状态',
            width: 70,
            slots: { default: 'status' },
          },
          {
            title: '操作',
            minWidth: 230,
            slots: { default: 'operation' },
          },
        ],
        style: '',
      })

      const handleEdit = (row, but) => {
        if (row) {
          state['editRef'].showEdit(row, but)
        } else {
          state['editRef'].showEdit({}, but)
        }
      }

      const handleDelete = (row) => {
        if (row) {
          $baseConfirm('你确定要删除当前项吗', null, async () => {
            const { code, data, msg } = await deleteDept(row.id)
            if (code === 0 || code === 200) {
              const row = state.myTree.getCurrentNode()
              const node = state.myTree.getNode(row.id) // 通过节点id找到对应树节点对象
              node.data.leaf = false
              node.loaded = false
              node.expand()
              $baseMessage(msg, 'success')
            } else {
              $baseMessage(msg, 'error')
            }
            await fetchData()
          })
        }
      }

      const loadNode = (node, resolve) => {
        if (node.level === 0) {
          getList(node, resolve, '0')
        }
        if (node.level >= 1) {
          getList(node, resolve, node.data.id)
        }
      }

      const getList = (node, resolve, id) => {
        state.lazyLoading = true
        getDeptPage({
          parentId: id,
        })
          .then((response) => {
            state.lazyLoading = false
            if (response.code === 0 || response.code === 200) {
              response.data.forEach((item) => {
                item.children = []
              })
              const data = $XEUtils.toArrayTree(response.data, {
                parentKey: 'parentId',
                key: 'id',
                children: 'childNode',
              })
              return resolve(Object.assign([], data))
            } else {
              $baseMessage(response.msg, 'error')
            }
          })
          .catch((err) => {
            state.lazyLoading = false
          })
      }

      const fetchData = async (val) => {
        const row = state.myTree.getCurrentNode()
        if (row) {
          const node = state.myTree.getNode(row.id) // 通过节点id找到对应树节点对象
          node.data.leaf = false
          node.loaded = false
          node.expand()
          state.listLoading = true
          const { data } = await getDeptPage({
            parentId: row.id,
          })
          state['xGrid'].reloadData(data)
          state.listLoading = false
        } else {
          handleQueryClick()
        }
      }

      const formatDeptType = (row) => {
        let type = ''
        state.typeOptions.forEach((item) => {
          if (row.type === item.value) {
            type = item.label
          }
        })
        return type
      }

      const handleNodeClick = async (val) => {
        state.listLoading = true
        const { data } = await getDeptPage({
          parentId: val.id,
        })
        state['xGrid'].reloadData(data)
        state.listLoading = false
      }

      const handleQueryClick = async () => {
        state.listLoading = true
        const { data } = await getDeptPage({
          name: state.listQuery.name,
        })
        state['xGrid'].reloadData(data)
        state.listLoading = false
      }

      const allowDrop = (draggingNode, dropNode, type) => {
        if (type !== 'inner') {
          return false
        } else {
          return true
        }
      }

      const allowDrag = (draggingNode) => {
        return true
      }

      const nodeDrop = (draggingNode, dropNode, dropType, ev) => {
        getMove({
          targetInput: {
            id: draggingNode.data.id,
            parentId: draggingNode.data.parentId,
            name: draggingNode.data.name,
            sort: draggingNode.data.sort,
            code: draggingNode.data.code,
          },
          sourceInput: {
            id: dropNode.data.id,
            parentId: dropNode.data.parentId,
            name: dropNode.data.name,
            sort: dropNode.data.sort,
            code: dropNode.data.code,
          },
          dropType: dropType,
        }).then((response) => {
          if (response.code === 0 || response.code === 200) {
            dropNode.loaded = false
            dropNode.expand()
          } else {
            $baseMessage(response.msg, 'error')
          }
          state.listLoading = false
        })
      }

      const mouseleave = (data) => {
        data.show = false
      }

      const mouseenter = (evl, data) => {
        const top = evl.clientY - evl.offsetY
        const left = evl.target.getBoundingClientRect().left

        state.style = `top:${top - 4}px;left:${
          left + evl.target.offsetWidth - 5
        }px`
        data.show = true
      }

      onMounted(() => {
        //fetchData()
      })

      onBeforeMount(() => {
        window.addEventListener('resize', handleHeight)
      })

      onBeforeUnmount(() => {
        window.removeEventListener('resize', handleHeight)
      })

      const handleHeight = () => {
        state.height = $baseTableHeight(0)
      }

      return {
        ...toRefs(state),
        loadNode,
        handleEdit,
        handleDelete,
        fetchData,
        handleNodeClick,
        handleQueryClick,
        Plus,
        Edit,
        Delete,
        Search,
        formatDeptType,
        mouseleave,
        mouseenter,
        allowDrop,
        allowDrag,
        nodeDrop,
        hasPermission,
      }
    },
  })
</script>

<style lang="scss" scoped>
  $base: '.Dept-management';
  #{$base}-container {
    padding: 0 !important;
    background: $base-color-background !important;
  }

  .tree-con {
    width: 405px;
    border-right: 1px solid #e4e7ed;
  }

  .container {
    position: relative;
    width: 100%;
    overflow: hidden;
    white-space: nowrap;
  }

  .hs {
    min-height: $base-keep-alive-height;
    background-color: #fff;
  }

  .splitpanes__pane {
    display: flex;
    font-family: Helvetica, Arial, sans-serif;
    color: rgba(255, 255, 255, 0.6);
    background-color: rgb(255, 255, 255) !important;
  }

  ::v-deep .splitpanes__splitter {
    min-width: 16px !important;
    background-color: #f5f7fa !important;
  }
</style>
